﻿Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports log4net
Imports System.Web.Script.Serialization
Partial Class CopyVersionJob
    Inherits System.Web.UI.Page

    Public AlertText As String
    Public ScriptText As String

    Private Shared logger As ILog = LogManager.GetLogger("CopyVersion")

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Session.LCID = 2057
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If

        If WebGrid1.IsFlyPostBack = False Then
            'If IsPostBack = False Then
            '  Session("users") = "bb9233"
            ' Session.Add("PlanYear", 2557)
            PlanYearsTxt.Text = Val(Session("PlanYear"))
            ' Session("prefilter")=

            Dim Myversion As Integer
            Dim username As String = Session("users")

            Dim top_fct As String
            Dim version As Integer

            GetTopFct(username, PlanYearsTxt.Text, 1, top_fct, version)

            If Val(Session("RoleType")) = 5 Or Val(Session("RoleType")) = 1 Then
                top_fct = "0000"
            End If
            Session("TopFctr") = top_fct
            'Response.Write("top" & top_fct & "top" & version)
            'Exit Sub
            Dim FCTDataSet As New DataSet
            GetChildWithVersion(top_fct, PlanYearsTxt.Text, 1, FCTDataSet, Myversion)
            'Exit Sub
            Dim adap As New FundCenter2TableAdapters.fundCenterDetailTableAdapter
            If top_fct Is Nothing Then
                top_fct = "0000"
            End If
            Dim nowVersion As Integer = adap.getNowVersion(top_fct, PlanYearsTxt.Text)
            ' Response.Write(nowVersion & "/" & Myversion & "/" & version)
            If FCTDataSet.Tables("Items").Rows.Count < 2 Then
                ' Response.Redirect("Default.aspx")
            End If
            If nowVersion > Myversion Then
                coppy_btn.Visible = False
                ForceCopyBtn.Visible = False
            Else
                coppy_btn.Visible = True
                ForceCopyBtn.Visible = True
            End If
            HdUser.Value = Session("users")

            If Val(Session("RoleType")) = 5 Or Val(Session("RoleType")) = 1 Then ''copy 4 to 5 
                HdMyVersion.Value = 5
            Else
                HdMyVersion.Value = Myversion
            End If
            WebGrid1.DataSource = FCTDataSet.Tables("Items")

            'If lblJob.Visible = False Then
            Dim joblistAdapter As New JobListTableAdapters.JobListTableAdapter
            Dim datagrid As New DataTable
            datagrid = WebGrid1.DataSource
            Dim nowVersion1 As String = ""
            If datagrid.Rows.Count > 0 Then
                nowVersion1 = datagrid.Rows(0).Item("Now_version")
            End If
            Dim dtFail = joblistAdapter.GetDataFail(top_fct, PlanYearsTxt.Text, nowVersion1, Myversion)
            If dtFail.Rows.Count() > 0 Then
                Dim JobEnum As New JobEnum
                If dtFail.Rows(0)("JobStatus").ToString() = JobEnum.JobStatus.Fail.ToString() Then
                    lblCopyFail.Visible = True
                    Dim dFail As DateTime = DateTime.Parse(dtFail.Rows(0)("UpdateDate").ToString())
                    lblCopyFail.Text = "ระบบไม่สามารทำการ Copy ครั้งล่าสุด เมื่อวันที่ " & dFail.ToString("dd/MM/yyyy") & " เวลา " & dFail.ToString("HH:mm") & " ได้ <br>เนื่องจาก" & dtFail.Rows(0)("Remark").ToString()
                End If
            Else
                lblCopyFail.Visible = False
            End If
            'End If


            'End If

            'Dim countr As Integer = 0
            Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
            'countr = adapr.checkCopy(Session("TopFctr"), version, Val(Session("PlanYear")))

            Dim lastflag As String = ""
            Try
                lastflag = adapr.GetLastFlag(Session("TopFctr"), version, Val(Session("PlanYear")))
            Catch ex As Exception
                lastflag = ""
                logger.Error(ex.Message)
                logger.Error(ex.StackTrace)
            End Try

            Dim reflag As String = ""
            Try
                reflag = adapr.GetReleaseFlag(Session("TopFctr"), version, Val(Session("PlanYear")))
            Catch ex As Exception
                reflag = ""
                logger.Error(ex.Message)
                logger.Error(ex.StackTrace)
            End Try

            If nowVersion = version Then
                If reflag = "N" And lastflag = "Y" Then
                    ImageButton1.Visible = True
                Else
                    ImageButton1.Visible = False
                End If
            Else
                ImageButton1.Visible = False
            End If
            If nowVersion = 1 Then
                ImageButton1.Visible = False
            End If
        End If
        'Response.Write(Session("TopFctr") & " " & nowVersion)
        If Session("pageindex") IsNot Nothing Then
            WebGrid1.SetCurrentPageIndex(Val(Session("pageindex")))
            Session.Remove("pageindex")
        End If
    End Sub

    Sub GetChildWithVersion(FundCenterCode As String, PlanYear As Decimal, FctGroup As String, ByRef ds As DataSet, ByRef CopyToVersion As Integer)


        Dim dt As DataTable = ds.Tables.Add("Items")
        dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
        dt.Columns.Add("FundCenterName", Type.GetType("System.String"))
        dt.Columns.Add("now_version", Type.GetType("System.Int32"))
        dt.Columns.Add("level", Type.GetType("System.Int32"))

        dt.Columns.Add("CreateDate", Type.GetType("System.String"))
        dt.Columns.Add("ReleaseFlag", Type.GetType("System.String"))
        Dim Radapter As New FundCenterRelationTableAdapters.FundCenterReleasesTableAdapter
        Dim Rdatatable As New FundCenterRelation.FundCenterReleasesDataTable
        Dim Fadapter As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
        Dim Fdatatable As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
        Dim Hadapter As New FundCenterRelationTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterRelation.FctHDataTable
        Dim Cdatatable As New FundCenterRelation.FctHDataTable
        Dim Badapter As New FundCenterRelationTableAdapters.BudgetDetailsTableAdapter

        Hdatatable = Hadapter.GetDataByFctCode(FundCenterCode, PlanYear, FctGroup)
        Dim RootGroupPath As String = ""

        If Hdatatable.Count = 0 Then
            Exit Sub
        End If
        Dim r As DataRow
        'add root
        For Each Hrow As FundCenterRelation.FctHRow In Hdatatable
            RootGroupPath = Hrow.grouppath
            r = dt.NewRow()
            r("FundCenterCode") = Hrow.FundCenter_FundCenterCode
            r("FundCenterName") = Hrow.Description
            r("level") = Val(Left(Fadapter.GetOrgLevel(Hrow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
            'level=Org Level
            CopyToVersion = r("level")
            'Now version fix =1
            r("now_version") = 1
            'fundcenterreleases table 
            Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

            r("CreateDate") = ""
            r("ReleaseFlag") = ""
            For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                r("ReleaseFlag") = rrow.ReleaseFlag
            Next
            If r("ReleaseFlag") = "" Then
                'Budgetdeatail table
                If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                    r("ReleaseFlag") = "N"
                End If
            End If
            dt.Rows.Add(r)
        Next
        'get child 1 level
        Hdatatable = Hadapter.GetDataByGroupPath(RootGroupPath & "__", PlanYear, FctGroup)
        Dim version As Integer
        'add in temp Table
        For Each row As FundCenterRelation.FctHRow In Hdatatable
            r = dt.NewRow()
            r("FundCenterCode") = row.FundCenter_FundCenterCode
            r("FundCenterName") = row.Description
            'level=Org Level
            r("level") = Val(Left(Fadapter.GetOrgLevel(row.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
            'get child all
            Cdatatable = Hadapter.GetDataByGroupPath(row.grouppath & "%", PlanYear, FctGroup)
            If Cdatatable.Count = 0 Then 'If child have = 0
                r("now_version") = 1 'now version is 1
            Else
                r("now_version") = r("level") 'now version is Orglevel
            End If
            version = r("now_version")
            'FundCenterReleasesTableAdapter
            Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

            r("CreateDate") = ""
            r("ReleaseFlag") = ""
            For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable

                r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                r("ReleaseFlag") = rrow.ReleaseFlag
            Next
            If r("ReleaseFlag") = "" Then
                If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                    r("ReleaseFlag") = "N"
                End If
            End If

            dt.Rows.Add(r)
            'insert child
            For Each crow As FundCenterRelation.FctHRow In Cdatatable
                r = dt.NewRow()
                r("FundCenterCode") = crow.FundCenter_FundCenterCode
                r("FundCenterName") = crow.Description

                r("level") = Val(Left(Fadapter.GetOrgLevel(crow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))

                r("now_version") = version

                Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

                r("CreateDate") = ""
                r("ReleaseFlag") = ""
                For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                    r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                    r("ReleaseFlag") = rrow.ReleaseFlag
                Next
                If r("ReleaseFlag") = "" Then
                    If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                        r("ReleaseFlag") = "N"
                    End If
                End If
                dt.Rows.Add(r)
            Next



        Next

    End Sub


    Sub GetTopFct(username As String, PlanYear As Decimal, FctGroup As String, ByRef fctCode As String, ByRef version As Integer)
        Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
        Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable
        datatable = adapter.GetTopFctByUser(username, PlanYear, FctGroup)
        'Response.Write(username & "/" & PlanYear & "/" & FctGroup)
        Try
            If datatable.Rows.Count > 0 Then
                For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
                    fctCode = row.FundCenter_FundCenterCode
                    Dim level As Integer = Val(Left(row.OrgLevel, 1))
                    version = level
                Next
            End If
        Catch ex As Exception
            fctCode = ""
            version = 1
        End Try


    End Sub

    'Sub GetChildWithVersion(FundCenterCode As String, PlanYear As Decimal, FctGroup As String, ByRef ds As DataSet, ByRef version As Integer)


    '    Dim dt As DataTable = ds.Tables.Add("Items")
    '    dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
    '    'dt.Columns.Add("version", Type.GetType("System.Int32"))
    '    dt.Columns.Add("level", Type.GetType("System.Int32"))
    '    dt.Columns.Add("FundCenterName", Type.GetType("System.String"))
    '    dt.Columns.Add("CreateDate", Type.GetType("System.String"))
    '    dt.Columns.Add("ReleaseFlag", Type.GetType("System.String"))
    '    dt.Columns.Add("Now_version", Type.GetType("System.Int32"))
    '    Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
    '    Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable
    '    Dim Myversion As Integer = 1

    '    Dim r As DataRow
    '    r = dt.NewRow()
    '    r("FundCenterCode") = FundCenterCode
    '    r("Now_version") = 1

    '    Dim level As Integer

    '    level = adapter.GetLevel(FundCenterCode, PlanYear, FctGroup) / 10
    '    'MsgBox(FundCenterCode & "/" & PlanYear & "/" & FctGroup)
    '    'MsgBox(level)
    '    'Response.Write("/" & FundCenterCode)
    '    ' Exit Sub
    '    If level = 0 Then
    '        level = adapter.GetLevelByChild(FundCenterCode, PlanYear, FctGroup) / 10
    '    End If

    '    r("Level") = level
    '    HdMyVersion.Value = level
    '    version = level

    '    ' Response.Write(FundCenterCode & PlanYear & version)
    '    'Response.Write(HdMyVersion.Value & "/" & level)
    '    Dim fadapter As New FundCenter2TableAdapters.FundCentersTableAdapter
    '    r("FundCenterName") = fadapter.GetName(FundCenterCode, PlanYear)
    '    Dim adap2 As New FundCenter2TableAdapters.fundCenterDetailTableAdapter
    '    For Each row As FundCenter2.fundCenterDetailRow In adap2.GetDataFundCenter(FundCenterCode, PlanYear, version)

    '        r("CreateDate") = row.CreatedDate.ToLongDateString
    '        Try
    '            r("ReleaseFlag") = row.ReleaseFlag
    '        Catch ex As Exception
    '            r("ReleaseFlag") = "N"
    '        End Try

    '        'r("Now_version") = row.Version
    '    Next

    '    'MsgBox(version)

    '    dt.Rows.Add(r)

    '    datatable = adapter.GetDataByParent(FundCenterCode, PlanYear, FctGroup)
    '    For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
    '        GetChild(FundCenterCode, row.FundCenter_FundCenterCode, ds, dt, PlanYear, FctGroup, version)
    '    Next




    'End Sub
    'Sub GetChild(top_code As String, ByVal parent_id As String, ByRef ds As DataSet, ByRef dt As DataTable, PlanYear As Decimal, FctGroup As String, parent_version As Decimal)

    '    Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
    '    Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable
    '    datatable = adapter.GetDataByParent(parent_id, PlanYear, FctGroup)
    '    Dim ChildAmount As Decimal
    '    Dim Relate As Decimal
    '    Dim r As DataRow
    '    Dim version As Integer = 1
    '    r = dt.NewRow()
    '    r("FundCenterCode") = parent_id

    '    ChildAmount = adapter.CountChild(parent_id, PlanYear, FctGroup)
    '    Relate = adapter.CountRelate(top_code, parent_id, PlanYear, FctGroup)
    '    If ChildAmount = 0 And Relate > 0 Then
    '        r("Now_version") = 1
    '    Else
    '        version = parent_version - 1
    '        r("Now_version") = version


    '    End If
    '    Dim level As Integer

    '    level = adapter.GetLevel(parent_id, PlanYear, FctGroup) / 10
    '    If level = 0 Then
    '        level = adapter.GetLevelByChild(parent_id, PlanYear, FctGroup) / 10
    '    End If
    '    Dim fadapter As New FundCenter2TableAdapters.FundCentersTableAdapter
    '    r("FundCenterName") = fadapter.GetName(parent_id, PlanYear)
    '    r("level") = level
    '    'Response.Write(level)
    '    Dim adap2 As New FundCenter2TableAdapters.fundCenterDetailTableAdapter
    '    For Each row As FundCenter2.fundCenterDetailRow In adap2.GetDataFundCenter(parent_id, PlanYear, version)

    '        r("CreateDate") = row.CreatedDate.ToLongDateString
    '        Try
    '            r("ReleaseFlag") = row.ReleaseFlag
    '        Catch ex As Exception
    '            r("ReleaseFlag") = "N"
    '        End Try
    '    Next

    '    dt.Rows.Add(r)

    '    For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
    '        GetChild(top_code, row.FundCenter_FundCenterCode, ds, dt, PlanYear, FctGroup, parent_version)
    '    Next
    'End Sub


    Protected Sub WebGrid1_InitializeDataSource(sender As Object, e As DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        'Dim Myversion As Integer
        'Dim username As String = Session("users")

        'Dim top_fct As String
        'top_fct = GetTopFct(username, PlanYearsTxt.Text, 1)
        'Dim FCTDataSet As New DataSet
        'GetChildWithVersion(top_fct, PlanYearsTxt.Text, 1, FCTDataSet, Myversion)
        'HdMyVersion.Value = Myversion
        'WebGrid1.DataSource = FCTDataSet.Tables("Items")
    End Sub


    Protected Sub WebGrid1_InitializePostBack(sender As Object, e As PostbackEventArgs) Handles WebGrid1.InitializePostBack
        Dim sqlall As String = ""
        Dim sqlbd As String = ""
        Dim sqlrev As String = ""
        Dim batchadap As New FundCenter2TableAdapters.FCReleasesTableAdapter
        If e.Action = PostBackAction.Custom Then
            Dim joblistAdapter As New JobListTableAdapters.JobListTableAdapter
            Dim JobEnum As New JobEnum
            Dim user As String = Session("users")
            Dim datagrid As New DataTable
            datagrid = WebGrid1.DataSource
            Dim fundCenterCode As String = datagrid.Rows(0).Item("FundCenterCode")
            Dim planYear As String = Val(PlanYearsTxt.Text)
            Dim newVersion As String = HdMyVersion.Value
            Dim nowVersion As String = datagrid.Rows(0).Item("Now_version")
            Dim ActionType As String = TryCast(Request("type"), String)
            If ActionType = "1" Then 'Copy
                Dim count As Integer = 0
                Dim topcount As Integer = 0
                Dim adapRel As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                For Each row As DataRow In datagrid.Rows
                    Try
                        If row.Item("ReleaseFlag") = "N" And Val(row.Item("level")) < 4 Then
                            count = count + 1
                            Exit For
                        End If
                        If row.Item("ReleaseFlag") = "" Then
                            count = count + 1
                            Exit For
                        End If
                    Catch ex As Exception
                        count = count + 1
                        Exit For
                    End Try
                Next
                If count > 0 Then
                    WebGrid1.ClientAction.Alert("มีหน่วยงาน ยังไม่ได้ส่งแผน ไม่สามารถ Copy Version ได้ในขณะนี้")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide()")
                    Exit Sub
                End If
                topcount = Val(adapRel.CheckFundRelease(datagrid.Rows(0).Item("FundCenterCode"), Val(PlanYearsTxt.Text), newVersion))
                If topcount > 0 Then
                    WebGrid1.ClientAction.Alert("ระบบไม่สามารถ Copy Version ที่ทำการ Copy Version มาแล้วได้\nหากต้องการ Copy Version อีกครั้งให้ทำการ Release Version ก่อน จากนั้นทำการ Copy Version อีกครั้ง")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide()")
                    Exit Sub
                Else
                    Dim countJob = joblistAdapter.GetCountRow(fundCenterCode, planYear, nowVersion, newVersion)
                    If countJob > 0 Then
                        WebGrid1.ClientAction.Alert("ท่านได้ทำการ Copy แล้ว ระบบกำลังดำเนินการ")
                        WebGrid1.ClientAction.InvokeScript("TINY.box.hide()")
                        Exit Sub
                    Else
                        joblistAdapter.InsertJobList(JobEnum.JobName.Copy.ToString(), JobEnum.JobStatus.Submit.ToString(), user, fundCenterCode, planYear, Nothing, newVersion, user, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
                        logger.Info("User " & user & " submit copy plan to new version")
                        WebGrid1.ClientAction.Alert("บันทึกข้อมูล Copy Version เรียบร้อยแล้ว")
                        'WebGrid1.ClientAction.InvokeScript("formrefresh()")
                        WebGrid1.ClientAction.InvokeScript("TINY.box.hide()")
                    End If
                End If
            ElseIf ActionType = "2" Then 'Force copy
                Dim causeForce As String = HdCause.Value
                Dim adapRel As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim topcount As Integer = 0
                topcount = Val(adapRel.CheckFundRelease(datagrid.Rows(0).Item("FundCenterCode"), Val(PlanYearsTxt.Text), newVersion))
                If topcount > 0 Then
                    WebGrid1.ClientAction.Alert("ระบบไม่สามารถ Copy Version ที่ทำการ Copy Version มาแล้วได้\nหากต้องการ Copy Version อีกครั้งให้ทำการ Release Version ก่อน จากนั้นทำการ Copy Version อีกครั้ง")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide()")
                    Exit Sub
                Else
                    Dim countJob = joblistAdapter.GetCountRow(fundCenterCode, planYear, nowVersion, newVersion)
                    If countJob > 0 Then
                        WebGrid1.ClientAction.Alert("ท่านได้ทำการ Force copy แล้ว ระบบกำลังดำเนินการ")
                        WebGrid1.ClientAction.InvokeScript("TINY.box.hide()")
                        Exit Sub
                    Else
                        joblistAdapter.InsertJobList(JobEnum.JobName.Force.ToString(), JobEnum.JobStatus.Submit.ToString(), user, fundCenterCode, planYear, Nothing, newVersion, user, causeForce, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
                        logger.Info("User " & user & " submit force copy plan to new version")
                        WebGrid1.ClientAction.Alert("บันทึกข้อมูล Force Copy Version เรียบร้อยแล้ว")
                        'WebGrid1.ClientAction.InvokeScript("formrefresh()")
                        WebGrid1.ClientAction.InvokeScript("TINY.box.hide()")
                    End If
                End If
            Else 'Release
                Dim countJob = joblistAdapter.GetCountRow(fundCenterCode, planYear, nowVersion, newVersion)
                If countJob > 0 Then
                    WebGrid1.ClientAction.Alert("ระบบกำลังดำเนินการ Copy ไม่สามารถยกเลิกส่งแผนได้ในขณะนี้")
                    Exit Sub
                End If

                Dim data As String = TryCast(Request("data"), String)
                Dim dd = data.Split(",")
                Dim fundCen As String = dd(0)
                Dim version As String = dd(1)
                Dim countr As Integer = 0
                Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                countr = adapr.checkCopy(fundCen, HdMyVersion.Value, Val(Session("PlanYear")))
                Dim adaprNow As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim nversion As String = adaprNow.getNowVersion(fundCen, "Y", Val(Session("PlanYear")), "Y")
                If Val(nversion) < HdMyVersion.Value Then
                    Dim adapre As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                    adapre.ReleaseBackVersion("N", "Y", Session("users"), Date.Now, fundCen, Val(Session("PlanYear")), Val(nversion))
                    Dim parentfctr As String = ""
                    Dim adpparent As New FundCenterParentTableAdapters.FundCenterHierarchiesTableAdapter
                    Try
                        parentfctr = adpparent.GetParentFCTR(fundCen, Val(Session("PlanYear")))
                    Catch ex As Exception
                        parentfctr = ""
                        logger.Error(ex.Message)
                        logger.Error(ex.StackTrace)
                    End Try

                    Dim Fadapter As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
                    Dim lvl As Integer = Val(Left(Fadapter.GetOrgLevel(fundCen, Val(Session("PlanYear")), 1), 1))
                    Dim parentcount As Integer = nversion - lvl
                    If parentcount < 0 Then
                        parentcount = 0
                    End If
                    Dim dd2 As New DataTable
                    dd2 = WebGrid1.DataSource
                    If parentcount > 0 Then
                        For n = 1 To parentcount
                            Dim exist As Integer = 0
                            For Each row2 As DataRow In dd2.Rows
                                If row2.Item("FundCenterCode").ToString.Trim = parentfctr Then
                                    exist += 1
                                End If
                                If exist > 0 Then
                                    Exit For
                                End If
                            Next
                            If exist > 0 And Val(nversion) > 1 Then
                                adapre.ReleaseBackVersion("N", "Y", Session("users"), Date.Now, parentfctr, Val(Session("PlanYear")), Val(nversion))
                                Try
                                    parentfctr = adpparent.GetParentFCTR(parentfctr, Val(Session("PlanYear")))
                                Catch ex As Exception
                                    parentfctr = ""
                                    logger.Error(ex.Message)
                                    logger.Error(ex.StackTrace)
                                End Try
                            End If
                        Next
                    End If
                    logger.Info("User " & Session("users") & " release plan")
                    WebGrid1.ClientAction.Alert("ยกเลิกส่งแผน หน่วยงานนี้เรียบร้อยแล้ว")
                End If
            End If
            Session.Remove("pageindex")
            Session.Add("pageindex", WebGrid1.GetCurrentPageIndex())
            WebGrid1.ClientAction.InvokeScript("formrefresh()")
        End If
    End Sub

    Protected Sub WebGrid1_InitializeRow(sender As Object, e As RowEventArgs) Handles WebGrid1.InitializeRow
        Dim imag As New Image
        imag = CType(e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().FindControl("Image1"), Image)
        Try
            If e.Row.GetDataRow("ReleaseFlag") = "Y" Then

                imag.ImageUrl = "Images/planIc/sendIc.png"
                imag.ToolTip = "ส่งแผนแล้ว"
            ElseIf e.Row.GetDataRow("ReleaseFlag") = "N" Then
                imag.ImageUrl = "Images/planIc/nosend.png"
                imag.ToolTip = "ยังไม่ได้ส่งแผน"
            Else
                imag.ImageUrl = "Images/planIc/nobuild.png"
                imag.ToolTip = "ยังไม่ได้สร้างแผน"
            End If
        Catch ex As Exception
            imag.ImageUrl = "Images/planIc/nobuild.png"
        End Try


        Dim lb As New Label
        lb = CType(e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().FindControl("Label2"), Label)
        Dim shif As String = ""
        For i As Integer = 1 To Val(HdMyVersion.Value) - Val(e.Row.GetDataRow("level"))
            shif = shif & "--"
        Next
        lb.Text = shif
        ' MsgBox(HdMyVersion.Value & "/" & e.Row.GetDataRow("Now_version"))
        Try

            If HdMyVersion.Value = 1 Then
                'Dim imag2 As New Image
                'imag2 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image2"), Image)
                Dim imag3 As New Image
                imag3 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image3"), Image)

                'imag2.Visible = False
                imag3.Visible = False
            Else
                'Dim countr As Integer = 0
                'Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                'countr = adapr.checkCopy(e.Row.GetDataRow("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))

                'Dim imag2 As New Image
                'imag2 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image2"), Image)
                Dim imag3 As New Image
                imag3 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image3"), Image)

                'If countr > 0 Then

                '    imag2.Visible = True
                '    imag3.Visible = False
                'Else
                'check preversion
                '  Dim checknow As Integer
                Dim adaprNow As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim nversion As String = adaprNow.getNowVersion(e.Row.GetDataRow("FundCenterCode"), "Y", Val(Session("PlanYear")), "Y")

                If nversion = e.Row.GetDataRow("Now_version") Then
                    'imag2.Visible = False
                    'imag3.Visible = coppy_btn.Visible
                    imag3.Visible = True

                Else
                    'imag2.Visible = False
                    imag3.Visible = False
                End If

                'End If


            End If
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try


    End Sub


    Sub Alert(ByVal message As String)
        AlertText = "<script> alert('" & message & "');</script>"
    End Sub

    Protected Sub ImageButton1_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton1.Click

        Dim countr As Integer = 0
        Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
        Dim dd As New DataTable
        dd = WebGrid1.DataSource

        Dim adapfundAss As New copyverAdvanceDSTableAdapters.FundedProgramAssetsTableAdapter
        Dim adapfundPro As New copyverAdvanceDSTableAdapters.FundedProgramProjectsTableAdapter

        Dim batchadap As New FundCenter2TableAdapters.FCReleasesTableAdapter
        Dim sqlbd As String = ""


        For Each row As DataRow In dd.Rows
            countr = adapr.checkCopy(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))

            Dim adapre As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
            Dim preVersion As Integer = adapre.getPreVersion(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))

            'delete  budgetDetail,budget12,attachment,RevPlan,FundCenterRelease 

            Dim dtrow As New FundCenter2.BudgetDetailsDataTable
            Dim adapter As New FundCenter2TableAdapters.BudgetDetailsTableAdapter
            dtrow = adapter.GetBudget_id(row.Item("FundCenterCode"), Val(Session("PlanYear")), HdMyVersion.Value)

            Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter

            For Each rowId As FundCenter2.BudgetDetailsRow In dtrow    'copy budget,copy attatment
                sqlbd += BatchDelAtt(rowId.Id)
                'adapAt.DeleteReleaseAtt(rowId.Id)
                sqlbd += BatchDelfundAss(rowId.Id)
                'adapfundAss.DeleteBD(rowId.Id)
                sqlbd += BatchDelfundPro(rowId.Id)
                'adapfundPro.DeleteBD(rowId.Id)
            Next
            Try
                batchadap.Execute(sqlbd)
            Catch ex As Exception

            End Try
            sqlbd = ""

            adapter.DeleteReleaseBud(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))
            Dim adapRev As New FundCenter2TableAdapters.BudgetRevPlansTableAdapter
            adapRev.DeleteReleaseRev(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))
            Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
            adapBud12.DeleteRelease(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))

            adapre.DeleteReleaseFun(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))
            'Dim forceFlag As String = "N"
            'Try
            '    forceFlag = adapre.GetForceFlag(row.Item("FundCenterCode"), preVersion, Val(Session("PlanYear")))
            'Catch ex As Exception

            'End Try
            'If forceFlag = "Y" Then
            'adapre.ReleaseBackVersion3("Y", Session("users"), Date.Now, row.Item("FundCenterCode"), Val(Session("PlanYear")), preVersion)

            'Else
            adapre.ReleaseBackVersion2("Y", Session("users"), Date.Now, row.Item("FundCenterCode"), Val(Session("PlanYear")), preVersion)

            'End If

        Next

        AlertText = "<script> alert('Release แผนเรียบร้อยแล้ว');window.location = 'CopyVersionJob.aspx';</script>"
        Session.Remove("pageindex")
        Session.Add("pageindex", WebGrid1.GetCurrentPageIndex())
    End Sub

    Sub Get_data()

        Dim Myversion As Integer
        Dim username As String = Session("users")

        Dim top_fct As String
        Dim version As Integer
        GetTopFct(username, PlanYearsTxt.Text, 1, top_fct, version)

        Session("TopFctr") = top_fct
        'Response.Write("top" & top_fct & "top" & version)
        'Exit Sub
        Dim topflag As String = "Y"
        Dim FCTDataSet As New DataSet
        GetChildWithVersion(top_fct, PlanYearsTxt.Text, 1, FCTDataSet, Myversion)
        'Exit Sub
        Dim adap As New FundCenter2TableAdapters.fundCenterDetailTableAdapter
        Dim nowVersion As Integer = adap.getNowVersion(top_fct, PlanYearsTxt.Text)
        ' Response.Write(nowVersion & "/" & Myversion & "/" & version)
        If FCTDataSet.Tables("Items").Rows.Count < 2 Then
            ' Response.Redirect("Default.aspx")
        End If

        If nowVersion > Myversion Then
            coppy_btn.Visible = False
            ForceCopyBtn.Visible = False
        End If
        HdUser.Value = Session("users")
        HdMyVersion.Value = Myversion
        WebGrid1.DataSource = FCTDataSet.Tables("Items")
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()

    End Sub


    Function BatchInsert(ByVal planyear As Short, ByVal re_flag As String, ByVal last_flag As String, ByVal version As String, ByVal prev As String, ByVal create_date As DateTime, ByVal createby As String, ByVal fctr As String, ByVal fctr_year As Short) As String
        Dim sql As String = ""
        Dim credate As String = ConvertDateTimeTS(create_date)
        sql += " INSERT INTO FundCenterReleases (PlanYear, ReleaseFlag, LastVersionFlag, Version, PrevVersion, CreatedDate, CreatedBy, FundCenter_FundCenterCode, FundCenter_PlanYear)"
        sql += " VALUES (" & planyear & ",'" & re_flag & "','" & last_flag & "','" & version & "','" & prev & "'," & credate & ",'" & createby & "','" & fctr & "'," & fctr_year & ")"
        sql += "; "
        Return sql
    End Function


    Function BatchForce(ByVal planyear As Short, ByVal re_flag As String, ByVal last_flag As String, ByVal version As String, ByVal prev As String, ByVal create_date As DateTime, ByVal createby As String, ByVal fctr As String, ByVal fctr_year As Short, ByVal ForceFlag As String, ByVal ReleaseReason As String) As String
        Dim sql As String = ""
        Dim credate As String = ConvertDateTimeTS(create_date)
        sql += " INSERT INTO FundCenterReleases (PlanYear, ReleaseFlag, LastVersionFlag, Version, PrevVersion, CreatedDate, CreatedBy, FundCenter_FundCenterCode, FundCenter_PlanYear,ForceFlag,ReleaseReason)"
        sql += " VALUES (" & planyear & ",'" & re_flag & "','" & last_flag & "','" & version & "','" & prev & "'," & credate & ",'" & createby & "','" & fctr & "'," & fctr_year & ",'" & ForceFlag & "','" & ReleaseReason & "')"
        sql += "; "
        Return sql
    End Function

    Function BatchcopyAtt(ByVal new_id As String, ByVal old_bid As String) As String
        Dim sql As String = ""
        sql += " INSERT INTO Attachments SELECT ItemNo, Title, FileName, FileType, FileSize, MimeType, CreatedDate, UpdatedDate, CreatedBy, UpdatedBy, " & new_id & " AS BudgetDetail_Id, delete_flag"
        sql += " FROM  Attachments AS Attachments_1"
        sql += " WHERE (BudgetDetail_Id = " & old_bid & ")"
        sql += "; "
        Return sql
    End Function


    Function BatchcopyB12(ByVal newver As String, ByVal new_id As String, ByVal old_bid As String) As String
        Dim sql As String = ""
        sql += " INSERT INTO  Budget12  SELECT  PlanYear, BaseYear, '" & newver & "' as Version, FunctionalArea, FundedProgram, Amount1, Amount2, Amount3, Amount4, Amount5, Amount6, Amount7, Amount8, Amount9, "
        sql += " Amount10, Amount11, Amount12, ForecastYear1, ForecastYear2, ForecastYear3, ForecastYear4, ProductItemNo, CreatedDate, UpdatedDate, CreatedBy, UpdatedBy, "
        sql += " FundCenter_FundCenterCode, FundCenter_PlanYear, Fund_FundCode, Fund_PlanYear, Cmmt_CmmtCode, Cmmt_PlanYear, CmmtDetail_Id, ActivityType_PlanYear, "
        sql += " ActivityType_ActivityTypeCode, Activity_ActivityCode, Activity_PlanYear, Product_ProductCode, Product_PlanYear, Project_ProjectCode, Project_PlanYear, "
        sql += " Project_FundCenterCode, " & new_id & " as BudgetDetail_Id"
        sql += " FROM Budget12"
        sql += " WHERE        (BudgetDetail_Id = " & old_bid & ")"
        sql += "; "
        Return sql
    End Function


    Function BatchCopyRev(ByVal vers As String, ByVal r_id As String) As String
        Dim sql As String = ""
        sql += " INSERT INTO BudgetRevPlans   SELECT         PlanYear, BaseYear,'" & vers & "' as Version, ActualLastYear2, ActualLastYear1, ForecastLastYear1, ForecastCurYear, LastYearMonth1, LastYearMonth2, LastYearMonth3, "
        sql += " LastYearMonth4, LastYearMonth5, LastYearMonth6, LastYearMonth7, LastYearMonth8, LastYearMonth9, LastYearMonth10, LastYearMonth11, LastYearMonth12,"
        sql += " CurYearMonth1, CurYearMonth2, CurYearMonth3, CurYearMonth4, CurYearMonth5, CurYearMonth6, CurYearMonth7, CurYearMonth8, CurYearMonth9,"
        sql += " CurYearMonth10, CurYearMonth11, CurYearMonth12, CreatedDate, UpdatedDate, CreatedBy, UpdatedBy, FundCenter_FundCenterCode, FundCenter_PlanYear,"
        sql += " Product_ProductCode, Product_PlanYear, ProductItem_Id"
        sql += " FROM BudgetRevPlans"
        sql += " WHERE        (Id = " & r_id & ")"
        Return sql
    End Function

    Function BatchOldRelease(ByVal lastver As String, ByVal updatedate As DateTime, ByVal updateby As String, ByVal fctr As String, ByVal fctryear As Short, ByVal newver As String) As String
        Dim sql As String = ""
        Dim udate As String = ConvertDateTimeTS(updatedate)
        sql += " UPDATE FundCenterReleases"
        sql += " SET LastVersionFlag = '" & lastver & "', UpdatedDate = " & udate & ", UpdatedBy = '" & updateby & "'"
        sql += " WHERE (FundCenter_FundCenterCode = '" & fctr & "') AND (FundCenter_PlanYear = " & fctryear & ") AND (Version = '" & newver & "')"
        Return sql
    End Function

    Function BatchForceFlag(ByVal re_flag As String, ByVal up_date As DateTime, ByVal up_by As String, ByVal forceflag As String, ByVal remark As String, ByVal fctr As String, ByVal pyear As Short, ByVal vers As String) As String
        Dim sql As String = ""
        Dim udate As String = ConvertDateTimeTS(up_date)
        sql += " UPDATE FundCenterReleases"
        sql += " SET  ReleaseFlag = '" & re_flag & "', UpdatedDate = " & udate & ", UpdatedBy = '" & up_by & "', ForceFlag = '" & forceflag & "', Remark = '" & remark & "'"
        sql += " WHERE  (FundCenter_FundCenterCode = '" & fctr & "') AND (FundCenter_PlanYear = " & pyear & ") AND (Version = '" & vers & "')"
        Return sql
    End Function


    Function BatchDelAtt(ByVal bid As String) As String
        Dim sql As String = ""
        sql += "DELETE FROM Attachments WHERE (BudgetDetail_Id = " & bid & ")"
        Return sql
    End Function

    Function BatchDelfundAss(ByVal bid As String) As String
        Dim sql As String = ""
        sql += "DELETE FROM [FundedProgramAssets] WHERE (BudgetDetail_Id = " & bid & ")"
        Return sql
    End Function

    Function BatchDelfundPro(ByVal bid As String) As String
        Dim sql As String = ""
        sql += "DELETE FROM [FundedProgramProjects]  WHERE (BudgetDetail_Id = " & bid & ")"
        Return sql
    End Function

    Function ConvertDateTimeTS(ByVal InputDate As Date) As String

        Dim sDate, dDate, mDate, yDate, tDate, nowDate As String

        Dim format As [String] = "dd/MM/yyyy HH:mm:ss"
        sDate = InputDate.ToString(format)
        dDate = Mid(sDate, 1, 2)
        mDate = Mid(sDate, 4, 2)
        yDate = Mid(sDate, 7, 4)
        If Val(yDate) >= 2550 Then
            yDate = (Val(yDate) - 543).ToString
        End If
        tDate = Mid(sDate, 12, 8)
        nowDate = "{ts '" & yDate & "-" & mDate & "-" & dDate & " " & tDate & "'}"
        Return nowDate
    End Function

End Class

